using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;

namespace Dotnet.DB
{
    public partial class DbBase
    {
        //protected string dbProviderName = "";//ConfigurationManager.AppSettings["DbHelperProvider"];
        //protected string dbConnectionString = "";//@"Data Source=H:\00OSC\01PROJ\PROJ.Tools\DbTool\bin\Debug\exampledb\mpdata.mdb;Provider=Microsoft.Jet.OLEDB.4.0;User ID=admin;Jet OLEDB:Database Password='mp611'"; //ConfigurationManager.AppSettings["DbHelperConnectionString"];
        private double _useTime = 0;
        private string _strSql = "";
        private DbConnection connection;
        public string ConnectionString
        {
            get;set;
        }

        #region 构造与初始化
        public DbBase()
        {
            //this.connection = CreateConnection(dbConnectionString);
        }
        //public DbBase(string connectionString)
        //{
        //    //this.connection = CreateConnection(connectionString);
        //}

        //public virtual DbConnection CreateConnection()
        //{
        //    dbfactory = DbProviderFactories.GetFactory(dbProviderName);
        //    connection = dbfactory.CreateConnection();
        //    connection.ConnectionString =dbConnectionString;
        //    return connection;
        //}
        public DbConnection CreateConnection(string connectionString)
        {
            ConnectionString = connectionString;
            //dbfactory = DbProviderFactories.GetFactory(dbProviderName);
            Connection = DbFactory.CreateConnection();
            Connection.ConnectionString = connectionString;
            return Connection;
        }
        #endregion

        #region 属性
        protected virtual DbProviderFactory DbFactory
        {
            get
            {
                throw new Exception("未设置DbFactory");
            }
        }

        public double UseTime { get => _useTime; set => _useTime = value; }
        public virtual string Database
        {
            get { return Connection.Database; }
        }

        public DbConnection Connection { get => connection; set => connection = value; }
        public string Sql { get => _strSql; set => _strSql = value; }
        #endregion

        #region Command参数创建

        public DbCommand GetStoredProcCommond(string storedProcedure)
        {
            DbCommand dbCommand = Connection.CreateCommand();
            dbCommand.CommandText = storedProcedure;
            dbCommand.CommandType = CommandType.StoredProcedure;
            return dbCommand;
        }
        public DbCommand GetSqlStringCommond(string sqlQuery)
        {
            DbCommand dbCommand = Connection.CreateCommand();
            dbCommand.CommandText = sqlQuery;
            dbCommand.CommandType = CommandType.Text;
            return dbCommand;
        }
        #endregion

        #region 参数方法
        public void AddParameterCollection(DbCommand cmd, DbParameterCollection dbParameterCollection)
        {
            foreach (DbParameter dbParameter in dbParameterCollection)
            {
                cmd.Parameters.Add(dbParameter);
            }
        }
        public void AddOutParameter(DbCommand cmd, string parameterName, DbType dbType, int size)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Size = size;
            dbParameter.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(dbParameter);
        }
        public void AddInParameter(DbCommand cmd, string parameterName, DbType dbType, object value)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Value = value;
            dbParameter.Direction = ParameterDirection.Input;
            cmd.Parameters.Add(dbParameter);
        }
        public void AddReturnParameter(DbCommand cmd, string parameterName, DbType dbType)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(dbParameter);
        }
        public DbParameter GetParameter(DbCommand cmd, string parameterName)
        {
            return cmd.Parameters[parameterName];
        }

        #endregion

        #region 执行 DataTable,DataSet,DataReader,ExecuteNonQuery,ExecuteScalar
        public DataSet ExecuteDataSet(DbCommand cmd)
        {
            //dbfactory = DbProviderFactories.GetFactory(dbProviderName);
            DbDataAdapter dbDataAdapter = DbFactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            dbDataAdapter.Fill(ds);
            return ds;
        }

        public DataTable ExecuteDataTable(DbCommand cmd)
        {
            Stopwatch sw = Stopwatch.StartNew();
            try
            {
                //dbfactory = DbProviderFactories.GetFactory(dbProviderName);     
                DbDataAdapter dbDataAdapter = DbFactory.CreateDataAdapter();
                dbDataAdapter.SelectCommand = cmd;
                DataTable dataTable = new DataTable();
                dbDataAdapter.Fill(dataTable);
                return dataTable;
            }
            catch (Exception ex)
            {
                throw new Exception($"【连接串】{connection.ConnectionString} 【SQL】{cmd.CommandText} 【异常】{ex.Message}");
            }
            finally
            {
                _strSql = cmd.CommandText;
                _useTime = Math.Round(sw.Elapsed.TotalMilliseconds, 2);
            }
        }


        public DbDataReader ExecuteReader(DbCommand cmd)
        {
            cmd.Connection.Open();
            DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            return reader;
        }
        public int ExecuteNonQuery(DbCommand cmd)
        {
            int ret = 0;
            Stopwatch sw = Stopwatch.StartNew();
            try
            {
                cmd.Connection.Open();
                ret = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception($"【连接串】{connection.ConnectionString} 【SQL】{cmd.CommandText} 【异常】{ex.Message}");
            }
            finally
            {
                cmd.Connection.Close();
                _strSql = cmd.CommandText;
                _useTime = Math.Round(sw.Elapsed.TotalMilliseconds, 2);
            }
            return ret;
        }
        public int ExecuteNonQuery(string strSql)
        {
            DbCommand cmd = connection.CreateCommand();
            cmd.CommandText = strSql;
            return ExecuteNonQuery(cmd);
        }



        public object ExecuteScalar(DbCommand cmd)
        {
            object ret = null;
            Stopwatch sw = Stopwatch.StartNew();
            try
            {
                if (cmd.Connection.State == ConnectionState.Closed)
                {
                    cmd.Connection.Open();
                }
                ret = cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw new Exception($"【连接串】{connection.ConnectionString} 【SQL】{cmd.CommandText} 【异常】{ex.Message}");
            }
            finally
            {
                cmd.Connection.Close();
                _strSql = cmd.CommandText;
                _useTime = Math.Round(sw.Elapsed.TotalMilliseconds, 2);
            }
            return ret;
        }
        #endregion

        #region 带有事务DataTable,DataSet
        public DataSet ExecuteDataSet(DbCommand cmd, Trans t)
        {
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            //dbfactory = DbProviderFactories.GetFactory(dbProviderName);
            DbDataAdapter dbDataAdapter = DbFactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            dbDataAdapter.Fill(ds);
            return ds;
        }

        public DataTable ExecuteDataTable(DbCommand cmd, Trans t)
        {
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            //dbfactory = DbProviderFactories.GetFactory(dbProviderName);
            DbDataAdapter dbDataAdapter = DbFactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataTable dataTable = new DataTable();
            dbDataAdapter.Fill(dataTable);
            return dataTable;
        }

        public DbDataReader ExecuteReader(DbCommand cmd, Trans t)
        {
            cmd.Connection.Close();
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            DbDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            return reader;
        }
        public int ExecuteNonQuery(DbCommand cmd, Trans t)
        {
            cmd.Connection.Close();
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            int ret = cmd.ExecuteNonQuery();
            return ret;
        }

        public object ExecuteScalar(DbCommand cmd, Trans t)
        {
            cmd.Connection.Close();
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            object ret = cmd.ExecuteScalar();
            return ret;
        }
        #endregion
    }

    public class Trans : IDisposable
    {
        private DbConnection conn;
        private DbTransaction dbTrans;
        public DbConnection DbConnection
        {
            get { return this.conn; }
        }
        public DbTransaction DbTrans
        {
            get { return this.dbTrans; }
        }

        //public Trans()
        //{
        //    DbBase db = new DbBase();
        //    conn = db.CreateConnection();
        //    conn.Open();
        //    dbTrans = conn.BeginTransaction();
        //}
        public Trans(string connectionString)
        {
            DbBase db = new DbBase();
            conn = db.CreateConnection(connectionString);
            conn.Open();
            dbTrans = conn.BeginTransaction();
        }
        public void Commit()
        {
            dbTrans.Commit();
            this.Colse();
        }

        public void RollBack()
        {
            dbTrans.Rollback();
            this.Colse();
        }

        public void Dispose()
        {
            this.Colse();
        }

        public void Colse()
        {
            if (conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
            }
        }
    }
}